<template>
  <div class="task-history-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>任务历史</span>
          <div class="header-operations">
            <el-button type="primary" @click="refreshData">刷新</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="searchForm" ref="searchFormRef" :inline="true" class="search-form">
        <el-form-item label="关键词">
          <el-input v-model="searchForm.keyword" placeholder="搜索用户指令" clearable></el-input>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="taskHistoryList"
        border
        style="width: 100%"
      >
        <el-table-column prop="taskId" label="任务ID" width="180" />
        <el-table-column prop="userInstruction" label="用户指令" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="viewTaskResult(scope.row)">查看结果</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getCurrentUserTaskHistory, getMockCurrentUserTaskHistory } from '../../api/taskHistory'
import dayjs from 'dayjs'

// 路由
const router = useRouter()

// 搜索表单
const searchForm = reactive({
  keyword: '',
  startTime: '',
  endTime: ''
})

// 日期范围
const dateRange = ref([])

// 表单引用
const searchFormRef = ref(null)

// 表格数据
const loading = ref(false)
const taskHistoryList = ref([])
const allTaskHistory = ref([]) // 存储所有任务历史，用于前端过滤
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 处理日期变化
const handleDateChange = (val) => {
  if (val) {
    searchForm.startTime = val[0]
    searchForm.endTime = val[1]
  } else {
    searchForm.startTime = ''
    searchForm.endTime = ''
  }
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

// 获取任务历史列表
const getTaskHistoryList = async () => {
  loading.value = true
  try {
    const res = await getCurrentUserTaskHistory()
    if (res.code === 200) {
      allTaskHistory.value = res.data
      filterAndPaginateData()
    } else {
      ElMessage.error(res.message || '获取任务历史失败')
    }
  } catch (error) {
    console.error('获取任务历史失败', error)
    
    // 使用模拟数据
    try {
      const res = await getMockCurrentUserTaskHistory()
      allTaskHistory.value = res.data
      filterAndPaginateData()
    } catch (e) {
      ElMessage.error('获取任务历史失败')
    }
  } finally {
    loading.value = false
  }
}

// 过滤并分页数据
const filterAndPaginateData = () => {
  // 过滤数据
  let filteredData = [...allTaskHistory.value]
  
  // 关键词过滤
  if (searchForm.keyword) {
    const keyword = searchForm.keyword.toLowerCase()
    filteredData = filteredData.filter(item => 
      item.userInstruction && item.userInstruction.toLowerCase().includes(keyword)
    )
  }
  
  // 日期过滤
  if (searchForm.startTime && searchForm.endTime) {
    const startDate = dayjs(searchForm.startTime).startOf('day')
    const endDate = dayjs(searchForm.endTime).endOf('day')
    
    filteredData = filteredData.filter(item => {
      const itemDate = dayjs(item.createTime)
      return itemDate.isAfter(startDate) && itemDate.isBefore(endDate)
    })
  }
  
  // 更新总数
  total.value = filteredData.length
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  taskHistoryList.value = filteredData.slice(start, end)
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  filterAndPaginateData()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  filterAndPaginateData()
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  filterAndPaginateData()
}

// 重置搜索
const resetSearch = () => {
  searchFormRef.value.resetFields()
  dateRange.value = []
  searchForm.startTime = ''
  searchForm.endTime = ''
  currentPage.value = 1
  filterAndPaginateData()
}

// 刷新数据
const refreshData = () => {
  getTaskHistoryList()
}

// 查看任务结果
const viewTaskResult = (row) => {
  // 将任务ID存入sessionStorage
  sessionStorage.setItem('currentTaskId', row.taskId)
  
  // 跳转到AI研究页面
  router.push('/ai-research')
}

// 组件挂载时获取数据
onMounted(() => {
  getTaskHistoryList()
})
</script>

<style scoped>
.task-history-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>